//
//  VideoDetailScreen.swift
//  MagaCore
//
//  Created by MrMessy on 2023/4/30.
//

import SwiftUI

struct HTVideoDetailScreen: View {
    @EnvironmentObject private var var_store: HTAppStore
    @State private var var_id: String = ""
    @State private var var_seekTime: Int = 0
    @State private var var_epId: String = ""
    @State private var var_source: String = ""
    @State private var var_orientation = UIDeviceOrientation.portrait
    @State private var var_serverUrls: [HTServer]!
    @State private var var_animeInfo: HTAnime!
    @State private var var_animeTitle = ""
    @State private var var_animeRecommend: [HTRecommend]!
    @State private var var_selEp: HTEp!
    @State private var var_selEp_id: String!
    @State private var var_subList: [HTSub]?
    @State private var var_subtitleList: [HTSubtitle]?
    @State private var var_url: String = ""
    @State private var var_changeUrl: HTChangeUrl?
    @State private var var_showPortraitDialog = false
    @State private var var_showLandscapeDialog = false
    @State private var var_showSubTitle = false
    @State private var var_selectEp: (() -> Void)!
    @State private var var_nextEp: (() -> Void)!
    @State private var var_subTitleBtnClick: (() -> Void)!
    @State private var var_fullScreen: ((UIDeviceOrientation) -> Void)!
    @State private var var_palyerCurrentTime: Double! = 0.0
    @State private var var_delay: Double! = 0.0
    @State private var var_showSubTitleView = false
    @State private var var_showFullSubTitleView = false
    @State private var var_subState: HTEnumSubtitleState!
    @State private var var_isShowSubTitle: Bool = true
    @State private var var_progressRate: Double! = 0.0
    @State private var var_startTime: String = "00:00"
    @State private var var_during: Double = 0
    @State private var var_triggerTimesTriggered: [Double: Bool] = [:]
    @State private var var_rotateAngle: Angle = .degrees(0)
    @State private var var_curSubscribe: HTSubscribe?
    @State private var var_timeElapsed: TimeInterval = 0.0
    @State private var var_timer: Timer?
    @State private var var_viewDisappear: Bool = false
    @State private var var_serverUrlName: String = ""
    @State private var var_showPushToFeedback: Bool = false
    @State private var var_isLock: Bool = false
    /** 显示愿望列表*/
    @State private var var_showAddToWishListAlert: Bool = false
    
    init(var_id: String, var_epId: String = "", var_seekTime: String? = "", var_source: String = "") {
        _var_id = State(initialValue: var_id)
        _var_epId = State(initialValue: var_epId)
        _var_source = State(initialValue: var_source)
        _var_seekTime = State(initialValue: var_seekTime!.ht_time2second()) // 接收秒
        _var_isShowSubTitle = State(initialValue: UserDefaults.standard.string(forKey: HTConfig.STATIC_userDefaults_isShowSubtitle) == "1")
        _var_subState = State(initialValue: .htEnumDisable)
    }
    
    var body: some View {
        ZStack(alignment: .topLeading) {
            NavigationLink(destination: HTFeedbackScreen(), isActive: $var_showPushToFeedback) {
                EmptyView()
            }
            
            GeometryReader { geometry in
                HTPlayerView(var_animeInfo: $var_animeInfo, var_animeTitle: $var_animeTitle, var_url: $var_url, var_changeUrl: $var_changeUrl, var_orientation: $var_orientation, var_selectEP: $var_selectEp, var_nextEP: $var_nextEp, var_subTitleBtnClick: $var_subTitleBtnClick, var_fullScreen: $var_fullScreen, var_subtitleList: $var_subtitleList, var_subState: $var_subState, var_palyerCurrentTime: $var_palyerCurrentTime, var_delay: $var_delay, var_progressRate: $var_progressRate, var_startTime: $var_startTime, var_seekTime: $var_seekTime, var_during: $var_during, var_selEp: $var_selEp, var_source: $var_source, var_isLock: $var_isLock, var_curSubscribe: $var_curSubscribe)
                    .frame(width: var_orientation.isLandscape ? var_screenHeight : var_screenWidth,
                           height: var_orientation.isLandscape ? var_screenWidth : var_playerViewHeight)
                    .position(x: (var_orientation.isLandscape ? var_screenHeight : var_screenWidth) / 2, y: (var_orientation.isLandscape ? var_screenWidth : var_playerViewHeight) / 2)
                    .zIndex(10)
                
                ZStack(alignment: .leading){
                    VStack(spacing: 0){
                        VStack{}
                            .frame(width: var_orientation.isPortrait ? var_screenWidth : var_screenHeight, height: var_playerViewHeight)
                        
                        if (var_curSubscribe == nil) {
                            HTVipBannerView(var_selEp: $var_selEp, var_source: $var_source, var_animeInfo: $var_animeInfo)
                        }
                        
                        if (var_curSubscribe == nil) {
                            HTBannerAd()
                                .frame(width: var_orientation.isPortrait ? var_screenWidth : var_screenHeight, height: (UIDevice.current.userInterfaceIdiom == .pad) ? 90 : 50)
                                .background(Color(hex: "#f5f5f5"))
                        }
                        
                        ScrollView(showsIndicators: false) {
                            VStack(alignment: .leading, spacing: 0) {
                                // 信息视图
                                if (var_animeInfo != nil && var_serverUrls != nil) {
                                    HTInfoView(var_animeInfo: var_animeInfo, var_serverUrls: var_serverUrls, var_serverUrlName: $var_serverUrlName, var_selEp: $var_selEp, var_source: $var_source) { url in
                                        var_url = url
                                        var_changeUrl!(url)
                                    }
                                }
                                
                                // 选集视图
                                if (var_animeInfo != nil && var_selEp != nil) {
                                    HTEpView(var_selEp_id: $var_selEp_id, var_animeInfo: var_animeInfo, var_selEp: $var_selEp, var_source: $var_source, var_onShowDialog:  {
                                        var_showPortraitDialog = true
                                    }) { sel_ep in
                                        var_selEp = sel_ep
                                        var_selEp_id = sel_ep.var_id
                                        var_seekTime = 0
                                        ht_loadUrl(var_id: sel_ep.var_id ?? "")
                                        ht_loadSubTitle(var_id: sel_ep.var_id ?? "")
                                    }
                                }
                                
                                // 推荐视图
                                if (var_animeInfo != nil) {
                                    VStack(spacing: 30) {
                                        ForEach(0..<(var_animeRecommend ?? []).count, id:\.self) { index in
                                            let var_reco = (var_animeRecommend ?? [])[index]
                                            HTRecommendScrollView(var_selEp: $var_selEp, var_source: $var_source, var_animeInfo: var_animeInfo, var_reco: var_reco) { selAnime in
                                                ht_addRecentPlay()
                                                var_id = selAnime.var_id
                                                var_epId = ""
                                                var_seekTime = 0
                                                var_animeInfo = nil
                                                ht_loadDetailInfo(var_id: var_id)
                                            }
                                        }
                                    }
                                    .padding(.top, 30)
                                    .padding(.bottom, 30)
                                }
                            }
                        }
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                        .background(Color(hex: "#f5f5f5"))
                    }
                    .frame(maxWidth: var_orientation.isPortrait ? var_screenWidth : var_screenHeight, maxHeight: var_orientation.isPortrait ? var_screenHeight : var_screenWidth)
                }
                .rotationEffect(.degrees(var_orientation.isPortrait ? 0 : -90))
                .position(x: var_screenWidth / 2, y: var_screenHeight / 2)
                .frame(width: var_orientation.isPortrait ? var_screenWidth : var_screenHeight, height: var_orientation.isPortrait ? var_screenHeight : var_screenWidth)
                .background(Color.black)
                .zIndex(1)
                
                if !var_orientation.isPortrait {
                    VStack{}
                        .rotationEffect(.degrees(var_orientation.isPortrait ? 0 : -90))
                        .position(x: var_screenWidth / 2, y: var_screenHeight / 2)
                        .frame(width: var_orientation.isPortrait ? var_screenWidth : var_screenHeight, height: var_orientation.isPortrait ? var_screenHeight : var_screenWidth)
                        .background(Color.black)
                        .zIndex(2)
                }
            }
            
            
            // 竖屏选集弹框
            if var_showPortraitDialog {
                HTEpPortraitSelectView(var_selEp_id: $var_selEp_id, var_animeInfo: var_animeInfo, var_onHideDialog: {
                    var_showPortraitDialog = false
                }, var_onSelEp: { sel_ep in
                    var_showPortraitDialog = false
                    var_selEp = sel_ep
                    var_selEp_id = sel_ep.var_id
                    var_seekTime = 0
                    ht_loadUrl(var_id: sel_ep.var_id ?? "")
                    ht_loadSubTitle(var_id: sel_ep.var_id ?? "")
                })
                .zIndex(11)
            }
            
            // 横屏选集弹框
            if var_showLandscapeDialog {
                HTEpLandscapeSelectView(var_selEp_id: $var_selEp_id, var_animeInfo: var_animeInfo, var_onHideDialog: {
                    var_showLandscapeDialog = false
                }, var_onSelEp: { sel_ep in
                    var_showLandscapeDialog = false
                    var_selEp = sel_ep
                    var_selEp_id = sel_ep.var_id
                    var_animeTitle = sel_ep.var_title ?? ""
                    var_seekTime = 0
                    ht_loadUrl(var_id: sel_ep.var_id ?? "")
                    ht_loadSubTitle(var_id: sel_ep.var_id ?? "")
                })
                .zIndex(11)
            }
            
            // 字幕弹框
            if var_showSubTitleView {
                HTSubView(var_showSub: $var_showSubTitleView, var_open: $var_isShowSubTitle, var_subState: $var_subState, var_palyerCurrentTime: $var_palyerCurrentTime, var_delay: $var_delay, var_subList: $var_subList, var_isShowSubTitle: $var_isShowSubTitle, var_subtitleList: $var_subtitleList, var_pushToFeedback: {
                    var_showSubTitleView = false
                    var_orientation = .portrait
                    var_showPushToFeedback = true
                    
                })
                .zIndex(11)
            }
            
            // 全屏字幕弹框
            if var_showFullSubTitleView {
                HTSubFullView(var_showSub: $var_showFullSubTitleView, var_open: $var_isShowSubTitle, var_subState: $var_subState, var_palyerCurrentTime: $var_palyerCurrentTime, var_delay: $var_delay, var_subList: $var_subList, var_isShowSubTitle: $var_isShowSubTitle, var_subtitleList: $var_subtitleList, var_pushToFeedback: {
                    var_fullScreen(.portrait)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        var_showPushToFeedback = true
                    }
                })
                .zIndex(11)
            }
            
            /** 显示添加到wishlist的提示框*/
            HTAddToWishListAlertView(var_showAddToWishListAlert: var_showAddToWishListAlert)
        }
        .toolbar(.hidden,for: .tabBar)
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
        .background(Color.black)
        .navigationBarHidden(true)
        .edgesIgnoringSafeArea(.all)
        .ignoresSafeArea()
        .statusBar(hidden: var_orientation.isLandscape)
        .onChange(of: var_isLock, perform: { newValue in
            if newValue {
                var_screenRotator = .landscape
            } else {
                var_screenRotator = .all
            }
        })
        .onChange(of: var_orientation, perform: { newValue in
            if newValue == .portrait {
                var_showLandscapeDialog = false
                var_showFullSubTitleView = false
                var_animeTitle = var_selEp.var_title ?? ""
            } else if newValue == .landscapeLeft {
                var_showPortraitDialog = false
                var_showSubTitleView = false
            }
        })
        .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
            if var_viewDisappear {return}
            if var_isLock {
                HTTools.ht_updateInterfaceOrientations(orientation: var_orientation)
                return
            }
            let orientation = UIDevice.current.orientation
            if orientation == .portraitUpsideDown {
                if UIDevice.current.userInterfaceIdiom == .pad {
                    var_orientation = .portrait
                } else {
                    return
                }
            }
            if orientation.isPortrait {
                var_orientation = .portrait
            } else if orientation.isLandscape {
                var_orientation = orientation
            } else {
                print("未知方向")
            }
            HTTools.ht_updateInterfaceOrientations(orientation: var_orientation)
        }
        .onReceive(var_store.objectWillChange) { _ in
            if var_viewDisappear {return}
            var_curSubscribe = var_store.state.var_subscribeState.var_curSubscribe ?? nil
        }
        // MARK: - 添加或者移除到wishlist时，触发
        .onReceive(NotificationCenter.default.publisher(for: HTConfig.STATIC_notification_addToWishListAlert), perform: { obj in
            if let userInfo = obj.userInfo  as? [String : Bool],
               let addToWishListAlert = userInfo["isAddTowishList"] {
                var_showAddToWishListAlert = addToWishListAlert
            }
        })
        .onAppear() {
            HTTools.ht_updateInterfaceOrientations(orientation: .portrait)
            var_viewDisappear = false
            ht_startTimer()
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                var_screenRotator = .all
                NotificationCenter.default.post(name: HTConfig.STATIC_notification_colorScheme, object: nil, userInfo: ["key": "dark"])
            }
            var_curSubscribe = var_store.state.var_subscribeState.var_curSubscribe ?? nil
            // 点击全屏/退出全屏
            var_fullScreen = { value in
                HTTools.ht_updateInterfaceOrientations(orientation: value)
                
                if value == .portrait {
                    var_orientation = .portrait
                } else if value == .landscapeLeft {
                    var_orientation = .landscapeLeft
                }
                
                HTNetworkManager().ht_requestForBuried(.htEnumMoviePlayCl(var_movie_id: var_animeInfo!.var_id, var_movie_name: var_animeInfo!.var_title ?? "", var_kid: "5", var_source: var_source, var_eps_id: var_selEp!.var_id ?? "", var_eps_name: var_selEp!.var_title ?? "", var_movielist_id: "", var_secname: "", var_subtitle: "1", var_m_type: "2", var_ori_type: var_orientation.isPortrait ? "1" : "2"))
            }
            // 点击字幕按钮
            var_subTitleBtnClick = {
                if var_orientation == .portrait {
                    var_showSubTitleView = true
                } else if var_orientation == .landscapeLeft || var_orientation == .landscapeRight {
                    var_showFullSubTitleView = true
                }
                
                HTNetworkManager().ht_requestForBuried(.htEnumMoviePlayCl(var_movie_id: var_animeInfo!.var_id, var_movie_name: var_animeInfo!.var_title ?? "", var_kid: "11", var_source: var_source, var_eps_id: var_selEp.var_id ?? "", var_eps_name: var_selEp.var_title ?? "", var_movielist_id: "", var_secname: "", var_subtitle: "1", var_m_type: "2", var_ori_type: var_orientation.isPortrait ? "1" : "2"))
            }
            // 全屏选集
            var_selectEp = {
                var_showLandscapeDialog = true
                HTNetworkManager().ht_requestForBuried(.htEnumMoviePlayCl(var_movie_id: var_animeInfo!.var_id, var_movie_name: var_animeInfo!.var_title ?? "", var_kid: "34", var_source: var_source, var_eps_id: var_selEp.var_id ?? "", var_eps_name: var_selEp.var_title ?? "", var_movielist_id: "", var_secname: "", var_subtitle: "1", var_m_type: "2", var_ori_type: "2"))
            }
            // 全屏下一级
            var_nextEp = {
                if var_animeInfo == nil {return}
                for i in 0..<var_animeInfo.ht_allEps().count {
                    let var_item = var_animeInfo.ht_allEps()[i]
                    if (var_selEp_id == var_item.var_id && i != var_animeInfo.ht_allEps().count - 1) {
                        var_selEp_id = var_animeInfo.ht_allEps()[i+1].var_id
                        var_selEp = var_animeInfo.ht_curEp(ep_id: var_selEp_id)
                        var_animeTitle = var_selEp.var_title ?? ""
                        ht_loadUrl(var_id: var_animeInfo.ht_allEps()[i+1].var_id ?? "")
                        ht_loadSubTitle(var_id: var_selEp.var_id ?? "")
                        break
                    }
                }
                HTNetworkManager().ht_requestForBuried(.htEnumMoviePlayCl(var_movie_id: var_animeInfo!.var_id, var_movie_name: var_animeInfo!.var_title ?? "", var_kid: "15", var_source: var_source, var_eps_id: var_selEp.var_id ?? "", var_eps_name: var_selEp.var_title ?? "", var_movielist_id: "", var_secname: "", var_subtitle: "1", var_m_type: "2", var_ori_type: var_orientation.isPortrait ? "1" : "2"))
            }
            // 加载数据
            if (var_animeInfo == nil) {
                ht_loadDetailInfo(var_id: var_id, isLoading: true)
            }
        }
        .onDisappear{
            var_viewDisappear = true
            ht_stopTimer()
            var_screenRotator = .portrait
            NotificationCenter.default.post(name: HTConfig.STATIC_notification_colorScheme, object: nil, userInfo: ["key": "light"])
            
            ht_addRecentPlay()
        }
    }
    
    // 获取信息
    private func ht_loadDetailInfo(var_id: String = "", isLoading: Bool = false) {
        var_store.dispatch(HTEnumAnimeAction.ht_recentPlayList(callback: { animes in
            if (isLoading) {
                for anime in (animes ?? []) {
                    if (anime.var_id == var_id) {
                        var_epId = anime.var_cur_epId ?? ""
                        var_seekTime = anime.var_startTime!.ht_time2second() // 接收秒
                    }
                }
            }
            
            var_store.dispatch(HTEnumAnimeAction.ht_animeInfo(params: ["id": var_id, "uid": "0" ], andCallback: { var_res in
                var_serverUrlName = ""
                var_animeInfo = var_res?.var_info
                var_animeRecommend = var_res?.var_reco
                var_selEp = var_animeInfo.ht_curEp(ep_id: var_epId)
                var_selEp_id = var_selEp.var_id
                var_animeTitle = var_selEp.var_title ?? ""
                ht_loadUrl(var_id: var_selEp.var_id ?? "")
                ht_loadSubTitle(var_id: var_selEp.var_id ?? "")
                
                HTNetworkManager().ht_requestForBuried(.htEnumMoviePlaySh(var_movie_id: var_animeInfo!.var_id, var_movie_name: var_animeInfo.var_title ?? "", var_source: var_source, var_eps_id: var_selEp.var_id ?? "", var_eps_name: var_selEp.var_title ?? "", var_movielist_id: "", var_status: "1", var_m_type: "2"))
            }))
        }))
    }
    
    // 获取地址
    private func ht_loadUrl(var_id: String = "", loadSuccess: (() -> Void) = {}) {
        var_store.dispatch(HTEnumAnimeAction.ht_animeUrls(params: ["id": var_id , "sig": "jE9TwyaLoyzTk1tTkdeMvE1Vw1eTk1pmjewdkE2ewdvUkE9TkdzMoyzS", "unixtime": Date().timeStamp ], andCallback: { var_res in
            var_serverUrls = var_res
            
            if let var_matchServerUrl = var_serverUrls.filter({$0.var_name == var_serverUrlName}).first {
                var_url = var_matchServerUrl.var_url
            } else {
                var_serverUrlName = var_serverUrls.count > 0 ? var_serverUrls[0].var_name : ""
                var_url = var_serverUrls.count > 0 ? var_serverUrls[0].var_url : ""
            }
            var_changeUrl!(var_url)
            
            if (var_curSubscribe == nil) {
                NotificationCenter.default.post(name: HTConfig.STATIC_notification_rewardedAd, object: nil, userInfo: ["status": "canshow"])
            }
        }))
    }
    
    // 获取字幕
    private func ht_loadSubTitle(var_id: String? = "") {
        var_store.dispatch(HTEnumAnimeAction.ht_subtitle(params: ["id": var_id ?? "", "type": "3"], andCallback: { var_subs in
            var_subList = var_subs ?? []
            var_subState = var_isShowSubTitle ? .htEnumOpen : .htEnumClose
            let var_subtitleLang = HTTools.ht_getSubTitlePreference()
            var var_selectIndex = -1
            for i in 0..<(var_subList ?? []).count {
                let var_item = var_subList![i]
                if var_item.var_lang == "English" { // 默认英语
                    var_selectIndex = i
                }
                if var_item.var_lang == var_subtitleLang {
                    var_selectIndex = i
                    break
                }
            }
            if var_selectIndex != -1 {
                ht_analysisSub(var_sub: var_subList![var_selectIndex])
            }
        }))
    }
    
    // 解析字幕
    private func ht_analysisSub(var_sub: HTSub) {
        var_delay = var_sub.var_delay ?? 0.0
        HTTools.ht_unzipFile(url: var_sub.var_sub ?? "") { var_subtitles in
            var_subtitleList = var_subtitles
        } andFail: {
            
        }
    }
    
    // 开始计时
    private func ht_startTimer() {
        if var_timer == nil {
            var_timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
                var_timeElapsed += 1
            }
        }
    }
    
    // 结束计时
    private func ht_stopTimer() {
        if (var_animeInfo != nil) {
            HTNetworkManager().ht_requestForBuried(.htEnumMoviePlayLen(var_movie_id: var_animeInfo!.var_id, var_movie_name: var_animeInfo!.var_title ?? "", var_eps_id: var_selEp.var_id ?? "", var_eps_name: var_selEp.var_title ?? "", var_watch_len: "\(var_timeElapsed)", var_source: var_source))
        }
        
        var_timer?.invalidate()
        var_timer = nil
        var_timeElapsed = 0.0
    }
    
    private func ht_addRecentPlay() {
        if (var_animeInfo != nil && var_animeInfo.var_id != "") {
            var var_curAnime = HTAnime()
            var_curAnime.var_id = var_animeInfo!.var_id
            var_curAnime.var_cover = var_animeInfo!.var_cover
            var_curAnime.var_title = var_animeInfo!.var_title
            var_curAnime.var_ep = var_animeInfo!.var_ep
            var_curAnime.var_cur_ep = "Ep \(var_selEp.var_eps_num ?? "")"
            var_curAnime.var_cur_epId = var_selEp.var_id
            var_curAnime.var_progressRate = var_progressRate
            var_curAnime.var_startTime = var_startTime
            var_curAnime.var_during = var_during
            var_store.dispatch(HTEnumAnimeAction.ht_addRecentPlay(anime: var_curAnime))
        }
    }
}
